// 在导入任何模块之前设置警告过滤器和错误处理器，以捕获所有警告和错误
// 抑制 Element Plus 的 type.text 弃用警告和 apiSign 警告
// 在升级到 Element Plus 3.0 后，可以将 type="text" 改为 type="link"

// 首先添加全局错误处理器来捕获 ResizeObserver 错误（必须在最前面）
if (typeof window !== 'undefined') {
  // 捕获同步错误（使用 capture 模式，在事件冒泡之前捕获）
  const errorHandler = (event) => {
    const errorMsg = event.message || event.error?.message || String(event.error || '');
    if (errorMsg.includes('ResizeObserver loop completed with undelivered notifications') ||
        errorMsg.includes('ResizeObserver loop limit exceeded')) {
      event.preventDefault();
      event.stopPropagation();
      event.stopImmediatePropagation();
      return false;
    }
  };
  
  // 在捕获阶段监听错误
  window.addEventListener('error', errorHandler, true);
  
  // 也监听冒泡阶段的错误（双重保险）
  window.addEventListener('error', errorHandler, false);

  // 捕获未处理的 Promise 错误
  window.addEventListener('unhandledrejection', (event) => {
    const reason = event.reason;
    if (reason) {
      const reasonStr = typeof reason === 'string' ? reason : 
                       (reason?.message || String(reason));
      if (reasonStr.includes('ResizeObserver loop completed with undelivered notifications') ||
          reasonStr.includes('ResizeObserver loop limit exceeded')) {
        event.preventDefault();
        event.stopPropagation();
        return false;
      }
    }
  });
  
  // 重写 ResizeObserver 构造函数，捕获内部错误
  if (window.ResizeObserver) {
    const OriginalResizeObserver = window.ResizeObserver;
    window.ResizeObserver = class extends OriginalResizeObserver {
      constructor(callback) {
        super((entries, observer) => {
          try {
            callback(entries, observer);
          } catch (error) {
            const errorMsg = error?.message || String(error);
            if (errorMsg.includes('ResizeObserver loop completed with undelivered notifications') ||
                errorMsg.includes('ResizeObserver loop limit exceeded')) {
              // 静默忽略 ResizeObserver 错误
              return;
            }
            throw error;
          }
        });
      }
    };
  }
}

// 过滤 console.warn 中的警告（需要在导入 api.js 之前设置）
const originalConsoleWarn = console.warn;
console.warn = function(...args) {
  // 检查所有参数
  const shouldFilter = args.some(arg => {
    if (!arg) return false;
    try {
      const argStr = typeof arg === 'string' ? arg : 
                    (typeof arg === 'object' && arg !== null && typeof arg.toString === 'function' ? arg.toString() : 
                    String(arg));
      return argStr.includes('type.text is about to be deprecated') ||
             argStr.includes('apiSign.sign is using temporary implementation') ||
             argStr.includes('[el-checkbox] [API] label act as value is about to be deprecated') ||
             argStr.includes('[ElPagination] Deprecated usages detected') ||
             (argStr.includes('ElementPlusError') && (
               argStr.includes('label act as value is about to be deprecated') ||
               argStr.includes('Deprecated usages detected')
             ));
    } catch (e) {
      // 如果转换失败，使用默认的字符串转换
      try {
        return String(arg).includes('type.text is about to be deprecated') ||
               String(arg).includes('apiSign.sign is using temporary implementation') ||
               String(arg).includes('[el-checkbox] [API] label act as value is about to be deprecated') ||
               String(arg).includes('[ElPagination] Deprecated usages detected') ||
               (String(arg).includes('ElementPlusError') && (
                 String(arg).includes('label act as value is about to be deprecated') ||
                 String(arg).includes('Deprecated usages detected')
               ));
      } catch (e2) {
        return false;
      }
    }
  });
  
  if (shouldFilter) {
    return;
  }
  originalConsoleWarn.apply(console, args);
};

// 同时过滤 console.error 中可能出现的 Element Plus 错误和 ResizeObserver 警告
const originalConsoleError = console.error;
console.error = function(...args) {
  // 检查是否是 Element Plus 的弃用警告或 ResizeObserver 警告
  const shouldFilter = args.some(arg => {
    if (!arg) return false;
    try {
      const argStr = typeof arg === 'string' ? arg : 
                    (typeof arg === 'object' && arg !== null && typeof arg.toString === 'function' ? arg.toString() : 
                    String(arg));
      return argStr.includes('type.text is about to be deprecated') ||
             (argStr.includes('ElementPlusError') && argStr.includes('type.text')) ||
             argStr.includes('ResizeObserver loop completed with undelivered notifications') ||
             argStr.includes('[el-checkbox] [API] label act as value is about to be deprecated') ||
             argStr.includes('[ElPagination] Deprecated usages detected');
    } catch (e) {
      // 如果转换失败，使用默认的字符串转换
      try {
        return String(arg).includes('type.text is about to be deprecated') ||
               (String(arg).includes('ElementPlusError') && String(arg).includes('type.text')) ||
               String(arg).includes('ResizeObserver loop completed with undelivered notifications') ||
               String(arg).includes('[el-checkbox] [API] label act as value is about to be deprecated') ||
               String(arg).includes('[ElPagination] Deprecated usages detected');
      } catch (e2) {
        return false;
      }
    }
  });
  
  if (shouldFilter) {
    return;
  }
  originalConsoleError.apply(console, args);
};

import { createApp } from 'vue';
import App from './App.vue';
import store from './store';
import router from './router';

import './global.less';
import 'element-plus/dist/index.css';

import registerBaseComponents from './global';
import maps from './utils/maps';
import api from '@/api/api';
import { buttonPermissionDirective } from '@/utils/buttonPermission';
import ButtonPermission from '@/components/common/ButtonPermission.vue';

// 自定义插件
import toast from './plugin/toast';
import deletePlugin from './plugin/delete';
import importPlugin from './plugin/import';
import elementInstallPlugin from './plugin/element';
import eventBus from './utils/eventBus';

const app = createApp(App);

// 过滤 Vue 的警告处理器
const originalWarnHandler = app.config.warnHandler;
app.config.warnHandler = (msg, instance, trace) => {
  // 过滤掉 Element Plus 的弃用警告和 ResizeObserver 警告
  const msgStr = msg?.toString() || '';
  if (msgStr.includes('type.text is about to be deprecated') || 
      (msgStr.includes('ElementPlusError') && msgStr.includes('type.text')) ||
      msgStr.includes('ResizeObserver loop completed with undelivered notifications') ||
      msgStr.includes('[el-checkbox] [API] label act as value is about to be deprecated') ||
      msgStr.includes('[ElPagination] Deprecated usages detected')) {
    return;
  }
  // 调用原始的警告处理器
  if (originalWarnHandler) {
    originalWarnHandler(msg, instance, trace);
  }
};

// Vue 应用错误处理器
app.config.errorHandler = (err, instance, info) => {
  const errStr = err?.message || err?.toString() || String(err);
  if (errStr.includes('ResizeObserver loop completed with undelivered notifications')) {
    // 忽略 ResizeObserver 错误
    return;
  }
  // 其他错误正常处理
  console.error('Vue Error:', err, info);
};

// 添加全局属性
app.config.globalProperties.$maps = maps;
app.config.globalProperties.$api = api;
app.config.globalProperties.$bus = eventBus;

app.use(store);
app.use(router);
app.use(toast);
app.use(deletePlugin);
app.use(importPlugin, { store });
app.use(elementInstallPlugin);

// 注册基础组件
registerBaseComponents(app);

// 注册按钮权限指令
app.directive('button-permission', buttonPermissionDirective);

// 注册按钮权限组件
app.component('ButtonPermission', ButtonPermission);

app.mount('#app');
